from rest_framework import serializers

from apps.index.models import Category, Task


class CategoriesSerializer(serializers.ModelSerializer):
    """分类序列化器类"""
    # 该字段信息通过下方的get_方法获取数据
    task = serializers.SerializerMethodField()

    class Meta:
        model = Category
        fields = '__all__'

    def get_task(self, task_obj):
        # 查询悬赏任务
        task_query_set = task_obj.category.all()
        # 遍历任务内容，并返回
        return {"result": [
            {'id': task_obj.id, 'name': task_obj.name, 'label': task_obj.label, 're_score': task_obj.re_score} for
            task_obj in task_query_set]}
